package eolympics.server;

import jexxus.common.Connection;
import minigames.IMiniGame;
import data.GameState;
import data.Player;
import eolympics.Communicator;

class GameServerWaitingForStartOfMiniGameState
        extends GameServerParentState
{
    public GameServerWaitingForStartOfMiniGameState(final IGameServer pGameServer)
    {
        super(pGameServer);

        chooseNextMiniGame();

        informClientsOfChosenMiniGame();
    }

    @Override
    public GameState getGameState()
    {
        return GameState.WAITING_FOR_START_OF_MINI_GAME;
    }

    private void informClientsOfChosenMiniGame()
    {
        for( Connection client : mServer.getClients() )
        {
            Communicator.sendChosenMiniGameToClient(client, mGameData.getCurrentMiniGame());
        }
    }

    private void chooseNextMiniGame()
    {
        if( mGameData.getCurrentMiniGame() == null )
        {
            mGameData.setCurrentMiniGame(mGameData.getMiniGames().get(0));
            return;
        }

        for( int i = 0; i < mGameData.getMiniGames().size(); i++ )
        {
            IMiniGame miniGame = mGameData.getMiniGames().get(i);
            if( mGameData.getCurrentMiniGame() == miniGame )
            {
                mGameData.setCurrentMiniGame(mGameData.getMiniGames().get(i + 1));
                return;
            }
        }

        throw new RuntimeException("mini game not found");
    }
    
    @Override
    public void playerIsReady( final Player pPlayerWhoIsReady )
    {
        boolean allPlayersReady = setPlayerReadyAndCheckIfAllPlayersAreReady(pPlayerWhoIsReady);

        if( allPlayersReady )
        {
            GameServerPlayingMiniGameState nextState = new GameServerPlayingMiniGameState(mGameServer);
            mGameServer.changeGameState(nextState);
        }
        else
        {
            mGameServer.sendPlayerListChangedToClients();
        }
    }
}
